import router from "@/router";

import NProgress from "nprogress"; // Progress 进度条
import "nprogress/nprogress.css"; // Progress 进度条样式
import { getToken } from "@/utils/auth";
import { useTagsStore } from '@/stores/tag.js'
import { useMenuStore } from '@/stores/menu.js'
import { cancelRequest }  from './request'
import { ElMessage,ElMessageBox } from 'element-plus'

const whiteList = [  
  "/login"
];

router.beforeEach((to, from, next) => {
  NProgress.start();
  nextPath(to, next,from);
});

router.afterEach(() => {
  NProgress.done(); // 结束Progress
});
async function nextPath(to, next,from) {
  const menuStore = useMenuStore();
  const tagsStore  = useTagsStore();
  let tagsName = tagsStore.tags.map(value=>value.name);
  if(to.name && !tagsName.includes(to.name)){
    if(tagsStore.tags && tagsStore.tags.length>=15){
      ElMessage({
        message: '打开页面最多为15个，请关闭其他页面后重新打开',
        type: "error",
      })
      next(false);
      NProgress.done()
    }
  }

  if (whiteList.includes(to.path)) {
    if(to.path == '/login'){
      if(getToken()){
        next('/');
        NProgress.done()
      }else{
        next();
      }
    }else{
      next();
    }
  }else{
    if (!getToken()) {
      next("/login");
      NProgress.done()
    } else {

      cancelRequest('');
      if(!to.name){
        menuStore.initRouteMenu();
        
        next({...to,replace:true})
      }else{
        tagsStore.changeActiveRouteName(to.name)
        next()
        NProgress.done()
      }
      




    }
  }

}

export default router;
